import React, { Component } from 'react'
import {
    StyleSheet,
    View,
    Text,
    Image,
    ListView,
    ScrollView,
    Platform,
    TouchableOpacity,
    TextInput,
    SectionList
} from 'react-native';

const Dimensions = require('Dimensions');
const { width } = Dimensions.get('window');

// common 
import NavigatorBar from '../../common/NavigationBar';
import BackPressComponent from '../../common/BackPressComponent';

import { searchAll } from '../../api/home'
// import { timingSafeEqual } from 'crypto';


export default class SearchPage extends Component {
    constructor(props) {
        super(props);
        global.log(props, '-----props');
        this.params = props.navigation.state.params;
        this.backPress = new BackPressComponent({ backPress: (e) => this.onBackPress(e) });
        // console.log(this.backPress,'backPress----')
        this.state = {
            searchSections: [],
            searchText: '',
            noData: false
        };
    }
    tabHandle(item) {
        global.log(item);
        this.setState({
            tabName: item
        })
    }

    // 渲染按钮
    renderLeftButton(image) {
        return <TouchableOpacity
            style={{ padding: 8 }}
            onPress={() => {
                this.props.navigation.goBack();
            }}>
            <Image
                style={{ width: 34, height: 34 }}
                source={image} />
        </TouchableOpacity>;
    }

    renderRightButton(image) {
        return <TouchableOpacity
            style={{ padding: 8 }}
            onPress={() => {
                this.props.navigation.goBack();
            }}>
            <Image
                style={{ width: 16, height: 14 }}
                source={image} />
        </TouchableOpacity>;
    }

    onBackPress(e) {
        
    }

    componentDidMount() {
        this.backPress.componentDidMount();
    }

    componentWillUnmount() {
        this.backPress.componentWillUnmount();
    }

    render() {

        return (
            <View style={styles.appContainer}>
                <NavigatorBar
                    hide={true}
                />
                {/* tree end */}
                {/* 搜索 */}
                <View style={styles.searchWrapper}>
                    <View style={styles.searchInput}>
                        <Image style={styles.searchIcon} source={require('../../assets/imgs/icon_search.png')} />
                        <TextInput autoFocus={true} returnKeyType={'search'}  placeholder="搜课程/老师/机构" onChangeText={(text) => this.handleChangeText(text)} underlineColorAndroid='transparent' style={styles.textInputStyle} placeholderTextColor={'#CCCCCC'}></TextInput>
                    </View>
                    <TouchableOpacity style={styles.filterSort} onPress={() => this.cancle()}>
                        <Text>取消</Text>
                    </TouchableOpacity>
                </View>
                {/* 搜索 end */}
                <ScrollView style={{ backgroundColor: '#F2F2F2' }}
                    showsVerticalScrollIndicator={false}
                >
                    <SectionList
                        renderItem={({ item, index, section }) => this.renderItem({ item, index, section })}
                        renderSectionHeader={({ section: { title, id, data } }) => (
                            <View key={id} style={data.length > 0 && styles.resWrapper}>{data.length > 0 ? <Text style={styles.headerTitle}>{title}</Text> : null}</View>
                        )}
                        sections={this.state.searchSections}
                        keyExtractor={(item, index) => item.ID || item.USERID}
                    />
                    {this.state.noData&&<View style={styles.noDataWrapper}><Text style={styles.noData}>暂无数据</Text></View>}
                </ScrollView>
            </View>
        )
    }
    handleHighlightText(str) {
        if (!str) return;
        // var textReg = new RegExp((this.state.searchText),'g');
        // global.log(textReg,'reg')
        // global.log(str,'uuuuu');
        // var mystr = str.replace(textReg, ($0,$1)=>{
        //     return <Text style={styles.itemHighlightText}>{this.state.searchText}</Text>
        // });
        // global.log(mystr,'my');  
        var pre = str.split(this.state.searchText)[0] && str.split(this.state.searchText)[0];
        var last = str.split(this.state.searchText)[1] && str.split(this.state.searchText)[1];
        return <Text>
            <Text>{pre}</Text><Text style={styles.itemHighlightText}>{this.state.searchText}</Text><Text>{last}</Text>
        </Text>;
    }
    // 渲染item
    renderItem({ item, index, section }) {
        var itemView = <View key={index}></View>;
        switch (item.TYPE) {
            case 'USERINFO':
                itemView = <TouchableOpacity style={styles.sectionItemWrapper} key={item.USERID} onPress={() => { this.goToDetail(item) }}>
                    <View><Text style={styles.itemText}>{this.handleHighlightText(item.NAME)}</Text></View>
                </TouchableOpacity>;
                break;
            case 'ORG':
                itemView = <TouchableOpacity style={styles.sectionItemWrapper} key={item.ID} onPress={() => { this.goToDetail(item) }}>
                    <View><Text style={styles.itemText}>{this.handleHighlightText(item.ORG_NAME)}</Text></View>
                </TouchableOpacity>;
                break;
            case 'COURSE':
                itemView = <TouchableOpacity style={styles.sectionItemWrapper} key={item.ID} onPress={() => { this.goToDetail(item) }}>
                    <View><Text style={styles.itemText}>{this.handleHighlightText(item.TITLE)}</Text></View>
                </TouchableOpacity>;
                break;
        }

        return (
            itemView
        )
    }
    // 处理搜索事件
    handleChangeText(text) {
        
        let mapData = {
            USERINFO: '老师',
            ORG: '机构',
            COURSE: '课程'
        }
        if (/^\s+|\s+$/.test(text)) return;
        if (!text) {
            this.setState({
                searchSections: [],
                noData: false
            });
            return;
        }
        
        this.setState({
            searchText: text
        });
        
        var resData = [];
        searchAll({ NAME: text }).then(res => {
            global.log(res, ' searchAll ')
            Object.keys(res).forEach((item, index) => {
                var allData = res[item].map(list => {
                    list.TYPE = item;
                    return list;
                })
                resData.push({ id: index, key: index, title: mapData[item], data: allData })
            });
            global.log(resData, '----');
            this.setState({
                searchSections: resData,
                noData: res.COURSE.length == 0 && res.ORG.length == 0 && res.USERINFO.length == 0
            })
        });
        // clearTimeout(this.timer)
        // this.timer = setTimeout(() => {
        //     // 查询所有数据
        //     alert(1212);
        //     var resData = [];
        //     searchAll({ NAME: text }).then(res => {
        //         global.log(res,' searchAll ')
        //         Object.keys(res).forEach((item, index) => {
        //             var allData = res[item].map(list => {
        //                 list.TYPE = item;
        //                 return list;
        //             })
        //             resData.push({ id: index, key: index, title: mapData[item], data: allData })
        //         });
        //         global.log(resData, '----');
        //         this.setState({
        //             searchSections: resData
        //         })
        //     });
        // }, 10)
    }
    // 跳转到详情
    goToDetail(item) {

        global.log(item,'item1111');
        // alert(item);
        if(item.TYPE == 'USERINFO') {
            this.props.navigation.navigate('TeaIntroduction',{
                teacherId: item.USERID
            })
        }
        else if(item.TYPE == 'ORG') {
            this.props.navigation.navigate('Mechanism', {
                ...item
            })
        }
        else {
            this.props.navigation.navigate('DetailLesson', {
                courseId: item.ID
            })
        }

    }

    cancle() {
       
        this.props.navigation.goBack();
        this.params && this.params.refreshPage && this.params.refreshPage();//返回上一个页面的refreshPage()
    }
}
const styles = StyleSheet.create({
    // 搜索页面
    appContainer: {
        flex: 1,
        backgroundColor: '#fff'
    },
    searchWrapper: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        paddingTop: 8,
        paddingBottom: 8,
        paddingLeft: 2,
        paddingRight: 2
    },
    searchIcon: {
        width: 14,
        height: 14,
        marginLeft: 10,
        marginRight: 5
    },
    searchInput: {
        width: width - 80,
        height: 36,
        backgroundColor: '#F7F7F9',
        borderRadius: 27,
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 15
    },
    textInputStyle: {
        width: 220,
        height: 36,
        fontSize: 12
    },
    filterSort: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    dropDownIcon: {
        width: 14,
        height: 14
    },
    // 
    resWrapper: {
        paddingLeft: 8,
        paddingRight: 8,
        paddingTop: 4,
        paddingBottom: 4,
        marginTop: 6,
        backgroundColor: '#fff'
    },
    headerTitle: {
        fontSize: 15
    },
    sectionItemWrapper: {
        paddingLeft: 8,
        paddingRight: 8,
        paddingTop: 4,
        paddingBottom: 4,
        backgroundColor: '#fff',
    },
    itemText: {
        fontSize: 16
    },
    itemHighlightText: {
        color: '#FF8A00'
    },
    noDataWrapper: {
        marginTop: 120,
        alignItems: 'center'
    },
    noData: {
        color: '#666'
    }
});